#!/usr/bin/python3

import os
import gettext
import signal
import gi
import distro
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk
from gi.repository.GdkPixbuf import Pixbuf

NORUN_FLAG = os.path.expanduser("~/.urukwelcome/urukwelcome/norun.flag")
#ORCA_RUN_FLAG = os.path.expanduser("/etc/xdg/autostart/orca-autostart.desktop")

# i18n
gettext.install("urukwelcome", "/usr/share/urukwelcome/locale")

signal.signal(signal.SIGINT, signal.SIG_DFL)


class UrukWelcome():

    def __init__(self):
        window = Gtk.Window()
        window.set_title(_("Welcome To Uruk GNU/Linux"))
        window.set_icon_from_file("/usr/share/urukwelcome/icons/logo.svg")
        window.set_position(Gtk.WindowPosition.CENTER)
        window.connect("destroy", Gtk.main_quit)
        
        disto = distro.linux_distribution()
        self.dist_name = (disto[0]).capitalize()
        codename = (disto[2]).capitalize()
        edition = (os.environ.get('DESKTOP_SESSION')).capitalize()
        release =  disto[1]
        infor = list(os.uname())
        welcome = "Welcome To Uruk GNU/Linux"
        desktop = (os.environ.get('DESKTOP_SESSION')).capitalize()
        #self.release_notes = config['RELEASE_NOTES_URL']
        #self.user_guide = "http://urukproject.org"  # Switch to config['USER_GUIDE_URL'] when mintdoc is ready and localized

        # distro-specific
        #self.dist_name = "Uruk GNU/Linux"


        current_theme = Gtk.Settings.get_default().get_property("gtk-theme-name")
        
        if(current_theme.startswith("Uruk-Y")):
            Uruk_Y_theme = True
            Uruk_Y_theme_html = " fgcolor='#3e3e3e'"
        else:
            Uruk_Y_theme = False
            Uruk_Y_theme_html = ""

        bgcolor = Gdk.RGBA()
        bgcolor.parse("rgba(0,0,0,0)")

        fgcolor = Gdk.RGBA()
        fgcolor.parse("#3e3e3e")

        main_box = Gtk.VBox()

        event_box = Gtk.EventBox()
        event_box.set_name("event_box")
        event_box.override_background_color(Gtk.StateType.NORMAL, bgcolor)
        main_box.pack_start(event_box, True, True, 0)

        vbox = Gtk.VBox()
        vbox.set_border_width(12)
        vbox.set_spacing(0)
        event_box.add(vbox)

        headerbox = Gtk.VBox()
        logo = Gtk.Image()
        logo.set_from_file("/usr/share/urukwelcome/icons/logo.svg")
        headerbox.pack_start(logo, False, False, 0)


        label = Gtk.Label()
        label.set_markup("<span font='14'" + Uruk_Y_theme_html + "> %s '<span fgcolor='#25AEDF'>%s</span>'</span>" % (welcome,release)) 
        headerbox.pack_start(label, False, False, 0)

        label1 = Gtk.Label()
        label1.set_markup("<span font='9'" + Uruk_Y_theme_html + "><i>%s %s</i> '<span fgcolor='#25AEDF'>%s </span>'</span> " % ("Release : ",codename,release))
        headerbox.pack_start(label1, False, False, 0)
        label1.set_line_wrap(True)

        label2 = Gtk.Label()
        label2.set_markup("<span font='9'" + Uruk_Y_theme_html + "><i>%s %s</i> '<span fgcolor='#25AEDF'>%s</span>'</span>" % ("Edition : ",desktop,infor[4]))
        headerbox.pack_start(label2, False, False, 0)

        label3 = Gtk.Label()
        label3.set_markup("<span font='9'" + Uruk_Y_theme_html + "><i>%s</i> '<span fgcolor='#25AEDF'>%s</span>'</span>" % ("Kernel : ",infor[2]))
        headerbox.pack_start(label3, False, False, 0)
        vbox.pack_start(headerbox, False, False, 0)

        welcome_label = Gtk.Label()
        welcome_message = _("Thank you for  choosing Uruk GNU/Linux, we hope you will enjoy using your new free operating system . Uruk GNU/Linux is a distribution of the GNU operating system, with the Linux-libre kernel.It comes ready for home and office use, and programs are easy to find and install.\nyou will find some usefull links below to help you starting with your new libre system :")
        welcome_label.set_markup("<span font='10'" + Uruk_Y_theme_html + ">%s</span>" % welcome_message)
        
        welcome_label.set_line_wrap(True)
        vbox.pack_start(welcome_label, False, False, 10)

        separator = Gtk.Image()
        separator.set_from_file('/usr/share/urukwelcome/icons/separator.png')
        vbox.pack_start(separator, False, False, 10)

        liststore = Gtk.ListStore(Pixbuf, str, str, str, Pixbuf, Pixbuf)
        self.iconview = Gtk.IconView.new()
        self.iconview.add_events(Gdk.EventMask.POINTER_MOTION_MASK)
        self.iconview.connect("item-activated", self.item_activated)
        self.iconview.connect("motion-notify-event", self.on_pointer_motion)
        self.iconview.connect("button-press-event", self.on_mouse_click)
        self.iconview.set_model(liststore)
        self.iconview.set_pixbuf_column(0)
        self.iconview.set_text_column(2)
        self.iconview.set_tooltip_column(3)
        self.iconview.set_columns(4)
        self.iconview.set_margin(0)
        self.iconview.set_spacing(6)
        self.iconview.set_item_padding(3)
        self.iconview.set_row_spacing(20)
        self.iconview.set_column_spacing(20)
        self.iconview.override_background_color(Gtk.StateType.NORMAL, bgcolor)
        if(Uruk_Y_theme):
            self.iconview.override_color(Gtk.StateType.NORMAL, fgcolor)
        #self.iconview.connect("selection-changed", self.item_activated)
        hbox = Gtk.HBox()
        hbox.pack_start(self.iconview, True, True, 30)
        vbox.pack_start(hbox, False, False, 10)
        
        hbox1 = Gtk.HBox()
        hbox1.pack_start(self.iconview, True, True, 30)
        vbox.pack_start(hbox1, False, False, 10)

        actions = []


        import apt
        cache = apt.Cache()

        self.last_selected_path = None

            
        #actions.append(['install_guix', _("Install GuixSD"), _("Install the latest release of free packages with guix package manager")])
        #actions.append(['user_guide', _("Documentation"), _("Learn more to get started with Uruk GNU/Linux")])
        #actions.append(['donors', _("Donations"), _("Make a donation to the Uruk project")])
        #actions.append(['chatroom', _("Chat room"), _("Chat live with other users in the irc chat room")])
        actions.append(['hardware', _("Hardware"), _("Find proper free drivers for your system")])
        actions.append(['software', _("Apps"), _("Install additional software")])
        actions.append(['forums', _("Forums"), _("Seek help from other users in the Free Software forums")])
        actions.append(['get_involved', _("Getting involved"), _("Find out how to get involved in the Uruk project")])
        actions.append(['fsf_gnu', _("FSF & GNU"), _("Find more about Free Software Foundation and GNU Project")])
        actions.append(['update', _("Update System"), _("Update your system")])
        actions.append(['setting', _("Open Control Center"), _("Open System Control Center")])
        actions.append(['issue', _("Bug Report"), _("Report any Bugs or issues that you find")])



        
        for action in actions:
            desat_pixbuf = Pixbuf.new_from_file('/usr/share/urukwelcome/icons/desat/%s.svg' % action[0])
            color_pixbuf = Pixbuf.new_from_file('/usr/share/urukwelcome/icons/color/%s.svg' % action[0])
            pixbuf = desat_pixbuf
            liststore.append([pixbuf, action[0], action[1], action[2], desat_pixbuf, color_pixbuf])

        hbox = Gtk.HBox()
        hbox.set_border_width(6)
        main_box.pack_end(hbox, False, False, 0)
        checkbox = Gtk.CheckButton()
        checkbox.set_label(_("Show this dialog at startup"))
        
        #hbox1 = Gtk.HBox()
        #hbox1.set_border_width(6)
        #main_box.pack_end(hbox1, False, False, 0)
        #checkbox1 = Gtk.CheckButton()
        #checkbox1.set_label(_("enable Screen Reader at startup"))

        if not os.path.exists(NORUN_FLAG):
            checkbox.set_active(True)
            
        #if os.path.exists(ORCA_RUN_FLAG):
            #checkbox1.set_active(True)

        checkbox.connect("toggled", self.on_button_toggled)
        hbox.pack_end(checkbox, False, False, 2)
        
        #checkbox1.connect("toggled", self.on_button1_toggled)
        #hbox1.pack_end(checkbox1, False, False, 2)

        window.add(main_box)
        window.set_default_size(540, 420)

        css_provider = Gtk.CssProvider()
        
        if(Uruk_Y_theme):
            css = """
            #event_box {
                background-image: -gtk-gradient (linear, left top, left bottom,
                from (#d6d6d6),
                color-stop (0.5, #efefef),
                to (#d6d6d6));
            }
            """
        else:
            css = """
            #event_box {
                background-color: @bg_color;
            }
            """

        css_provider.load_from_data(css.encode('UTF-8'))
        screen = Gdk.Screen.get_default()
        style_context = window.get_style_context()
        style_context.add_provider_for_screen(screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        window.show_all()

    def on_pointer_motion(self, widget, event):
        path = self.iconview.get_path_at_pos(event.x, event.y)
        if path != None:
            if path == self.last_selected_path:
                return
            self.unhighlight_icon(widget)
            treeiter = widget.get_model().get_iter(path)
            widget.get_model().set_value(treeiter, 0, widget.get_model().get_value(treeiter, 5))
            self.last_selected_path = path
        #If we're outside of an item, deselect all items (turn off highlighting)
        if path == None:
            self.unhighlight_icon(widget)
            self.iconview.unselect_all()

    def unhighlight_icon(self, widget):
        if self.last_selected_path != None:
            treeiter = widget.get_model().get_iter(self.last_selected_path)
            widget.get_model().set_value(treeiter, 0, widget.get_model().get_value(treeiter, 4))
            self.last_selected_path = None

    def on_button_toggled(self, button):
        if button.get_active():
            if os.path.exists(NORUN_FLAG):
                os.system("rm -rf %s" % NORUN_FLAG)
        else:
            os.system("mkdir -p ~/.urukwelcome/urukwelcome")
            os.system("touch %s" % NORUN_FLAG)
            
    #def on_button1_toggled(self, button):
        #if button.get_active():
            #if not os.path.exists(ORCA_RUN_FLAG):
                #os.system('gksu "cp /usr/lib/urukwelcome/urukwelcome/orca-autostart.desktop /etc/xdg/autostart"')
        #else:
            #os.system('gksu "rm -rf /etc/xdg/autostart/orca-autostart.desktop"')

    def on_mouse_click(self, widget, event):
        if event.type == Gdk.EventType.BUTTON_PRESS:
            path = self.iconview.get_path_at_pos(event.x, event.y)
            #if left click, activate the item to execute
            if event.button == 1 and path != None:
                self.item_activated(widget, path)

    def item_activated(self, view, path):
        treeiter = view.get_model().get_iter(path)
        value = view.get_model().get_value(treeiter, 1)

        if value == "forums":
            os.system("xdg-open https://trisquel.info/en/forum/general-free-software-talk &")
        elif value == "fsf_gnu":
            #os.system("xdg-open http://www.fsf.org/ &")
            os.system("xdg-open https://www.gnu.org/ &")
        elif value == "software":
            os.system("synaptic-pkexec  &")
        elif value == "hardware":
            os.system("xdg-open https://h-node.org/hardware/catalogue/en &")
        elif value == "get_involved":
            os.system("xdg-open https://urukproject.org/dist/en.html#involved &")
        elif value == "setting":
            os.system("mate-control-center &")
        elif value == "update":
            os.system('sudo /usr/lib/urukUpdater/checker | zenity --title="System Updating Info" --text="Checking your System for updates \n \n this may take a few minutes depending on your speed connection...." --no-cancel --progress --pulsate --width=400 --height=140 --auto-kill --auto-close --window-icon=/usr/share/urukUpdater/pixmap/wait.svg')
        elif value == "issue":
            os.system("xdg-open https://urukproject.org//bt/login_page.php  &")
        #elif value == "install_guix":
            #os.system("sh  &")


if __name__ == "__main__":
    UrukWelcome()
    Gtk.main()
